package com.simpleframe.domain.state;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import com.simpleframe.core.io.ClassPathResource;
import com.simpleframe.core.io.Resource;
import com.simpleframe.exception.SimpleframeException;
import com.simpleframe.util.XmlUtil;

/**
 * 本类用于初始化配置在state.xml 的状态
 * @author 刘甘露
 *
 */
public class StateContext {

	private static Map<String, Map<String, String>> stateConfigs;
	
	/**
	 * 状态项目初始化，该方法应在系统启动时调用
	 */
	public static void initStateConfigs(){
		System.out.println("============= 初始化状态配置文件 =============");
		if(stateConfigs==null){
			stateConfigs = new HashMap<String, Map<String,String>>();
			
			Resource resource = new ClassPathResource("state.xml");
			File file = null;
			try {
				file = resource.getFile();
			} catch (Exception e) {
				//throw new SimpleframeException("状态配置文件不存在");
				System.out.println("=============== 状态文件不存在 =================");
				return;
			}
			
			Document doc = null;
			try {
				doc = XmlUtil.getDocument(file);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if(doc==null){
				throw new SimpleframeException("状态配置文件 xml 不能转化为 document");
			}
			
			Element root = doc.getRootElement();
			Iterator<Element> it = root.elementIterator("state");
			while (it.hasNext()) {
				Element elem = it.next();
				String name = elem.attributeValue("name");
				String state = elem.attributeValue("state");
				stateConfigs.put(StringUtils.trim(name),stateToMap(StringUtils.trim(state)));
			}
		}
	}
	
	public static List<StateVo> getItemsList(String state){
		List<StateVo> list = new ArrayList<StateVo>();
		
		Map<String, String> map = getItemsMap(state);
		for (String name : map.keySet()) {
			StateVo sv = new StateVo();
			sv.setCode(name);
			sv.setTitle(map.get(name));
			list.add(sv);
		}
		
		return list;
	}
	
	public static Map<String, String> getItemsMap(String state){
		Map<String, String> map = new HashMap<String, String>();
		
		if(state!=null){
			state = state.trim();
			//直接在页面设置
			if(state.startsWith("{")){
				map = stateToMap(state); 
			}
			//来自配置文件
			else{
				if(stateConfigs.containsKey(state)){
					map = stateConfigs.get(state);
				}
			}
		}
		return map;
	}
	
	private static Map<String, String> stateToMap(String state){
		JSONObject jsonObject = JSONObject.fromObject(state);
		return (Map<String, String>)JSONObject.toBean(jsonObject, Map.class);
	}
}
